import sys
import System
import System.Threading
import clr
import time
import threading
import thread
import Queue
import nadgradnja
import SocketServer
import random
import time
from System.Net import *

#nadgradnja
try:
    hostname = Dns.GetHostName()
    print(hostname)
    if (hostname != "PURKAT"):
         nadgradnja.nadgradi()
except Exception, e:
    debug.TraceDbg("Nadgradnja ni uspela!", "%s" %(e.message.ToString()), "Warning")

clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("Microsoft.Scripting")
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')



from System import Action, AppDomain, UnhandledExceptionEventHandler, Windows
from System.Collections import *
clr.AddReferenceByPartialName('MySql.Data')
from MySql.Data.MySqlClient import *
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection
from System.Threading import *
from System.Threading.Tasks import *
from System.Windows.Threading import *
from System.Text.RegularExpressions import *
clr.AddReference("SAP_dll")
from SAP_dll import *
from System.ComponentModel import BackgroundWorker
from System.Windows import Window
from napake import *
from System.Windows.Controls import *
from System.Drawing import *



class StanjeIzdelka(object):
    def __init__(self):
        self._actual = None
    @property
    def some_value(self):
        return self._actual
    @some_value.setter
    def some_value(self, value):
        self._actual = value
    # 0 - zagon; error- nepravilni podatki
    # 1 - definiran izdelek, caka se na rezultat
    # 2 - izdelek definiran in ima rezultat
    # 3 - izdelek vpisan v bazo kot PASS
    # 4 - izdelek vpisan v bazo kot FAIL

class MyForm(Form):
   
    def __init__(self):
        self.Text = 'Vnos opombe'
        self.TopMost = 1

        button = System.Windows.Forms.Button()
        button.Location = Point(188, 203)
        button.Text = 'Prilozi'
        button.Click += self.kliknil
        self.Controls.Add(button)

        textbox_opombe = System.Windows.Forms.TextBox()
        textbox_opombe.Location = Point(13, 13)
        textbox_opombe.Size = Size(250, 184)
        textbox_opombe.Text = 'Vnesi opombe ...'
        textbox_opombe.Multiline = 1
        self.Controls.Add(textbox_opombe)
         
        self.textbox_fajl = System.Windows.Forms.TextBox()
        self.textbox_fajl.Location = Point(12, 203)
        self.textbox_fajl.Size = Size(170, 20)
        self.Controls.Add(self.textbox_fajl)

        #button = System.Windows.Forms.Button()
        #button.Location = Point(188, 243)
        #button.Text = 'Potrdi'
        #button.DialogResult = DialogResult.OK;
        #button.Click += potrdil
        #self.Controls.Add(button)

    def kliknil(self, sender, args):
        dialogl = OpenFileDialog()
        if dialogl.ShowDialog() == DialogResult.OK:
            self.textbox_fajl.Text = dialogl.FileName

    def opomba():
        return textbox_opombe.Text

#def potrdil(*args):
#    form.Close()

def onTick(sender, event):
    global lb_stevec
    lb_stevec.Content = int(lb_stevec.Content) + 1

class SocketHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        try:
            self.data = self.request.recv(1024).strip()
            serijska = self.data.ToString().Split(' ')[0]
            rezultat = self.data.ToString().Split(' ')[1]
        except Exception, e:
            serijska = "n/a"
            rezultat = "n/a"
        debug.TraceDbg("Prispelo sporocilo od %s: " % self.client_address[0], "String: %s -> SERIAL: %s RESULT: %s" %(self.data, serijska, rezultat), "Info")
        if (rezultat == "n/a" and serijska != "n/a"):
            obdelajS(serijska)
        if (rezultat != "n/a" and serijska != "n/a"):
            if (serijska == obrazec.label1_serijska_vobdelavi.Text.ToString()):
                obrazec.label1_rezultat_vobdelavi.Text = rezultat
            else:
                stop("Serijska v obdelavi %s in iz socketa %s se ne ujemata!" %(obrazec.label1_serijska_vobdelavi.Text.ToString(), serijska), 1)



IT_VERZIJA = "020"

conStrNtpe1 = 'server=ntpe1; userid=purkat; password=purkat; database=sledljivost;'
conStrPris = 'Data Source=vmie3;initial catalog=KAKOVOST;user id=uporabnik;password=uporabnik; Connect Timeout=30'
Procesne = ArrayList()
SerijskeSAP = ArrayList()
ProcesneSAP = ArrayList()
tip_naloga = ""
status_naloga = ""
TIPINALOGOV = {'ZCEN':'Standardni proizvodni nalog SI2000 ni k.', 
               'ZCIU':'Standardni proizvodni nalog IUT G.I.',
               'ZEM':'Standardni proizvodni nalog EMS',
               'ZEW':'Standardni proizvodni nalog EWSD',
               'ZGP':'Proizvodni nalog Garancijska popravila',
               'ZIU':'Standardni proizvodni nalog IUT',
               'ZIZ':'Proizvodni nalog za izmet',
               'ZLEM':'Proizvodni nalog za Lems',
               'ZNP':'Standardni proizvodni nalog NP',
               'ZPP':'Proizvodni nalog Predelava',
               'ZPT':'Proizvodni nalog za Prototipe',
               'ZRAZ':'Proizvodni nalog Razgradnja',
               'ZRIU':'Proizvodni nalog Razgradnja',
               'ZSAG':'Standardni proizvodni nalog EWSD ni kal.',
               'ZSE':'Proizvodni nalog za Servis',
               'ZSI':'Standardni proizvodni nalog SI2000'
               }

STATUSINALOGOV = {'H':'Homologacija',
                  'K':'Pilot + Homologacija',
                  'L':'Sprememba + Homologacija',
                  'M':'Vzorec + Homologacija',
                  'N':'Novo',
                  'P':'Pilot',
                  'PU':'Ponovno uvajanje',
                  'R':'Uvajanje P-zakljuceno',
                  'RS':'Uvajanje S-zakljuceno',
                  'S':'Sprememba',
                  'U':'Uvajanje v teku',
                  'RV':'vzorec V-zakljucen',
                  'V':'Vzorec',
                  '':'Normalni delovni nalog'
                  }




ID_izdelka = None
Opomba = ''
StanjeIzdelka.some_value = 444;
timer = Timer()
timer.Interval = 1000
timer.Tick += onTick
obrazec.tabItem3.IsEnabled = 0

#socket server
#def bg_socket(sender, args):
#    HOST, PORT = "localhost", 9999
#    server = SocketServer.TCPServer((HOST, PORT), SocketHandler)
#    server.serve_forever()
#workerS = BackgroundWorker()
#workerS.DoWork += bg_socket
#workerS.RunWorkerAsync()




# FUNKCIJE
stevec_poizvedb = 0
class ObjectLocker(object):
      def __init__(self, obj):
              self.obj = obj
      def __enter__(self):
              global stevec_poizvedb
              stevec_poizvedb += 1
              Monitor.Enter(self.obj)
      def __exit__(self, *args):
              global stevec_poizvedb
              stevec_poizvedb -= 1
              Monitor.Exit(self.obj)

def barva_obrazca(barva):    #{Red, Blue, Green};
    obrazec.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, Action[object](obrazec.ChangeGrid), barva)


def porocilo_nalog(sender, args):
    global Procesne
    global SerijskeSAP
    global ProcesneSAP
    stavek = ''
    index = 0
    if (ProcesneSAP.Count > 0):
        print("Porocilo vzeto iz SAPa : ")
        for indeks in range(0, ProcesneSAP.Count):
            try:    
                rezultat = poizvedbaPRIS("SELECT REZULTAT FROM SPREMNILISTREZULTAT WHERE ID IN (SELECT REZULTAT FROM SPREMNILISTIZDELKA WHERE ID IN (SELECT MAX(ID) FROM SPREMNILISTIZDELKA WHERE PROCESNA = '%s' AND OPERACIJA = '%s'))" %(ProcesneSAP[indeks].Substring(0,9), obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{REZULTAT}")
                if (rezultat.Count == 1):
                    stavek = stavek + str(indeks + 1) + ") " + ProcesneSAP[indeks] + " " + SerijskeSAP[indeks] + " - " + rezultat[0] + "\n"
                else:
                    stavek = stavek + str(indeks + 1) + ") " + ProcesneSAP[indeks] + " " + SerijskeSAP[indeks] + "\n"
                i = i + 1
            except Exception as e:
                debug.TraceDbg("Ne morem narediti porocila !", e.message.ToString(), "Warning")
    else:
        print("Porocilo vzeto iz ASYS : ")
        for indeks in range(0, Procesne.Count):
            try:    
                rezultat = poizvedbaPRIS("SELECT REZULTAT FROM SPREMNILISTREZULTAT WHERE ID IN (SELECT REZULTAT FROM SPREMNILISTIZDELKA WHERE ID IN (SELECT MAX(ID) FROM SPREMNILISTIZDELKA WHERE PROCESNA = '%s' AND OPERACIJA = '%s'))" %(Procesne[indeks].Substring(0,9), obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{REZULTAT}")
                if (rezultat.Count == 1):
                    stavek = stavek + str(indeks + 1) + ") " + Procesne[indeks] + " - " + rezultat[0] + "\n"
                else:
                    stavek = stavek + str(indeks + 1) + ") " + Procesne[indeks] + "\n"
            except Exception as e:
                debug.TraceDbg("Ne morem narediti porocila !", e.message.ToString(), "Warning")
    
                
    print(stavek)



def mouseclick(sender, args):
    obrazec.label1_procesna_vobdelavi.Text = sender.Content

def paralelno_environment(stevilo):
    status_parallel = System.Windows.Controls.Primitives.StatusBar()
    for pozicije in stevilo.ToString().Split(';'):
        lb_1 = Button()
        lb_1.Content = pozicije
        lb_1.Click += mouseclick
        status_parallel.Items.Add(lb_1)
    obrazec.stackPanel6.Children.Add(status_parallel)


def init(): # inicializacija stevcev
    global lb_nalog
    global lb_pass
    global lb_fail
    global lb_out
    global lb_todo
    global lb_stevec
    global tip
    global status


    lb_stevec.Content = "0"
    obrazec.stackPanel5.Children.Add(lb_stevec)

    lb_1 = Label()
    lb_1.Content = "NALOG"
    lb_1.Margin = System.Windows.Thickness(140, 240, 25, 5)
    lb_1.MouseUp += porocilo_nalog
    obrazec.uiGridMain.Children.Add(lb_1)
    lb_2 = Label()
    lb_2.Content = "PASS"
    lb_2.Margin = System.Windows.Thickness(140, 252, 25, 5)
    lb_2.MouseUp += porocilo_nalog
    obrazec.uiGridMain.Children.Add(lb_2)
    lb_3 = Label()
    lb_3.Content = "FAIL"
    lb_3.Margin = System.Windows.Thickness(140, 264, 25, 5)
    lb_3.MouseUp += porocilo_nalog
    obrazec.uiGridMain.Children.Add(lb_3)
    lb_4 = Label()
    lb_4.Content = "KARAN"
    lb_4.Margin = System.Windows.Thickness(140, 276, 25, 5)
    lb_4.MouseUp += porocilo_nalog
    obrazec.uiGridMain.Children.Add(lb_4)
    lb_5 = Label()
    lb_5.Content = "TODO"
    lb_5.Margin = System.Windows.Thickness(140, 288, 25, 5)
    lb_5.MouseUp += porocilo_nalog
    obrazec.uiGridMain.Children.Add(lb_5)



    lb_nalog.FontWeight = System.Windows.FontWeights.Bold
    lb_nalog.Foreground = System.Windows.Media.Brushes.Black
    lb_nalog.Margin = System.Windows.Thickness(180, 240, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_nalog)
    lb_pass.FontWeight = System.Windows.FontWeights.Bold
    lb_pass.Foreground = System.Windows.Media.Brushes.Green
    lb_pass.Margin = System.Windows.Thickness(180, 252, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_pass)
    lb_fail.FontWeight = System.Windows.FontWeights.Bold
    lb_fail.Foreground = System.Windows.Media.Brushes.Orange
    lb_fail.Margin = System.Windows.Thickness(180, 264, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_fail)
    lb_out.FontWeight = System.Windows.FontWeights.Bold
    lb_out.Foreground = System.Windows.Media.Brushes.Red
    lb_out.Margin = System.Windows.Thickness(180, 276, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_out)
    lb_todo.FontWeight = System.Windows.FontWeights.Bold
    lb_todo.Foreground = System.Windows.Media.Brushes.Blue
    lb_todo.Margin = System.Windows.Thickness(180, 288, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_todo)
    lb_nalog.Content = "n/a"
    lb_pass.Content = "n/a"
    lb_fail.Content = "n/a"
    lb_out.Content = "n/a"
    lb_todo.Content = "n/a"

                    



def osvezi_kolicine():
    try:
        worker_kolicine = BackgroundWorker()
        worker_kolicine.DoWork += bg_Poizvedba_PRIS
        worker_kolicine.RunWorkerCompleted += bg_osvezi_kolicine
        stavek_pass = "SELECT COUNT(*) FROM (SELECT PROCESNA, MAX(DATUM) as MaxTime FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE OPERACIJA IN ('%s') AND NALOG IN ('%s') AND (REZULTAT = 0 OR REZULTAT = 2 OR REZULTAT = 5) GROUP BY PROCESNA) r INNER JOIN SPREMNILISTIZDELKA t ON t.PROCESNA = r.PROCESNA AND t.DATUM = r.MaxTime AND t.REZULTAT = 0" %(obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_delnalogi.SelectedItem.ToString())
        stavek_fail = "SELECT COUNT(*) FROM (SELECT PROCESNA, MAX(DATUM) as MaxTime FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE OPERACIJA IN ('%s') AND NALOG IN ('%s') AND (REZULTAT = 0 OR REZULTAT = 2 OR REZULTAT = 5) GROUP BY PROCESNA) r INNER JOIN SPREMNILISTIZDELKA t ON t.PROCESNA = r.PROCESNA AND t.DATUM = r.MaxTime AND t.REZULTAT = 2" %(obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_delnalogi.SelectedItem.ToString())        
        stavek_karantena = "SELECT COUNT(*) FROM (SELECT PROCESNA, MAX(DATUM) as MaxTime FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE OPERACIJA IN ('%s') AND NALOG IN ('%s') AND (REZULTAT = 0 OR REZULTAT = 2 OR REZULTAT = 5) GROUP BY PROCESNA) r INNER JOIN SPREMNILISTIZDELKA t ON t.PROCESNA = r.PROCESNA AND t.DATUM = r.MaxTime AND t.REZULTAT = 5" %(obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_delnalogi.SelectedItem.ToString())        
        stavek_nalog = "SELECT STMODULOV FROM KAKOVOST.dbo.DELNALOGI WHERE DELNALOG IN ('%s')" %(obrazec.comboBox_delnalogi.SelectedItem.ToString())
        worker_kolicine.RunWorkerAsync(["SELECT (%s) as st, (%s) as pass, (%s) as fail, (%s) as karantena" %(stavek_nalog, stavek_pass, stavek_fail, stavek_karantena), "{st} {pass} {fail} {karantena}"])
    except Exception as e:
        brisiznake()
        debug.TraceDbg("Ne morem osveziti kolicin !", e.message.ToString(), "Warning")

def bg_osvezi_kolicine(sender, args):
    #print "Osvezujem kolicine ..."
    global lb_nalog
    global lb_pass
    global lb_fail
    global lb_out
    global lb_todo
   
    rezultat = args.Result[0].ToString().Split(' ')
    lb_nalog.Content = rezultat[0]
    lb_pass.Content = rezultat[1]
    lb_fail.Content = rezultat[2]
    lb_out.Content = rezultat[3]
    try:
        lb_todo.Content = int(rezultat[0].ToString()) - int(rezultat[1].ToString()) - int(rezultat[2].ToString()) - int(rezultat[3].ToString())
    except Exception as e:
        debug.TraceDbg("Ne morem preveriti kolicin v tabeli DELOVNINALOGI!", e.message.ToString(), "Warning")
        lb_todo.Content = "n\a"
    i = 0
#
# POVEZAVA Z SAP
#
def poizvedbaSAP(nalog):
    global SerijskeSAP
    global ProcesneSAP
    global tip_naloga
    global status_naloga
    with ObjectLocker(SAP400):
        barva_obrazca('Blue')
        resultat = None
        try:
            resultat = SAP400()
            resultat.getData(nalog)
            SerijskeSAP = resultat.SerijskeSAP()
            ProcesneSAP = resultat.ProcesneSAP()
            tip_naloga = resultat.tipDN()
            status_naloga = resultat.statusDN()
            debug.TraceDbg("Poizvedba na SAP uspesna!", resultat.SporociloSAP(), "Info")
        except Exception as e:
            debug.TraceDbg("Poizvedba na SAP neuspesna!", e.message.ToString(), "Warning")
        barva_obrazca('None')
        return resultat


#
# Poizvedba na NTPE1
#
def poizvedbaNTPE(stavek, izhod):
    dbNtpe1 = MySqlConnection(conStrNtpe1)
    l = ArrayList()
    i=0
    print("NTPE: %s" %stavek)
    with ObjectLocker(dbNtpe1):
        barva_obrazca('Blue')
        while dbNtpe1.State.ToString() != "Open":  
            try:
              dbNtpe1.Open()
              cmd = dbNtpe1.CreateCommand()
              cmd.CommandText = stavek
              r = cmd.ExecuteReader ()
              l = ArrayList()
              while r.Read ():
                  vrednost = izhod
                  for x in range(r.FieldCount):
                      vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                  l.Add(vrednost)
              r.Close ()
              barva_obrazca('None')
            except Exception as e:
              debug.TraceDbg("Povezava na NTPE1 neuspesna!", e.message.ToString(), "Warning")
              System.Threading.Thread.Sleep(2000)
              if (i<2):
                barva_obrazca('Orange')
              else:
                barva_obrazca('Red')
              i=i+1
        dbNtpe1.Close ()
        return l


#
# POVEZAVA Z PRIS
#
def poizvedbaPRIS(stavek, izhod):
    dbPris = SqlConnection(conStrPris)
    l = ArrayList()
    i = 0
    print("PRIS: %s" %stavek)
    with ObjectLocker(dbPris):
        barva_obrazca('Blue')
        while dbPris.State.ToString() != System.Data.ConnectionState.Open.ToString():
            try:
                dbPris.Open()
                cmd = dbPris.CreateCommand()
                cmd.CommandText = stavek
                r = cmd.ExecuteReader ()
                l = ArrayList()
                while r.Read ():
                    vrednost = izhod
                    for x in range(r.FieldCount):
                        vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                    l.Add(vrednost)
                r.Close ()
                barva_obrazca('None')
            except Exception as e:
                debug.TraceDbg("Povezava na PRIS neuspesna!", "Stavek: %s\n%s" %(stavek, e.message.ToString()), "Warning")
                System.Threading.Thread.Sleep(1000)
                if (i<2):
                    barva_obrazca('Orange')
                else:
                    barva_obrazca('Red')
                i=i+1
        dbPris.Close ()
        return l

def bg_Poizvedba_PRIS(sender, args):
    tmp = poizvedbaPRIS(args.Argument[0], args.Argument[1])
    args.Result = tmp

def bg_Poizvedba_NTPE(sender, args):
    tmp = poizvedbaNTPE(args.Argument[0], args.Argument[1])
    args.Result = tmp

def bg_Poizvedba_SAP(sender, args):
    tmp = poizvedbaSAP(args.Argument[0], args.Argument[1])
    args.Result = tmp

def info(message = '', show=0):
    if (show):
        obrazec.image_info.Visibility = System.Windows.Visibility.Visible
        obrazec.image_info.ToolTip = '%s' %(message);
    else:
        obrazec.image_info.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_info.ToolTip = ''

def stop(message = '', show=0):
    if (show):
        ok()
        obrazec.image_stop.Visibility = System.Windows.Visibility.Visible
        obrazec.image_stop.ToolTip = '%s' %(message);
    else:
        obrazec.image_stop.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_stop.ToolTip = '';

def ok(message = '', show=0):
    if (show):
        stop()
        obrazec.image_ok.Visibility = System.Windows.Visibility.Visible
        obrazec.image_ok.ToolTip = '%s' %(message);
    else:
        obrazec.image_ok.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_ok.ToolTip = '';

def warning(message = '', show=0):
    if (show):
        obrazec.image_warning.Visibility = System.Windows.Visibility.Visible
        obrazec.image_warning.ToolTip = '%s' %(message);
    else:
        obrazec.image_warning.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_warning.ToolTip = ''

def brisiznake():
    info()
    stop()
    warning()
    ok()



# M A I N #

debug.TraceDbg("Skripta EE-offline verzije %s" %(IT_VERZIJA), "Offline nacin", "Info")



# izdelki
def bg_izdelki(sender, args):
    obrazec.label_status.Content = ''
    izdelki = args.Result
    obrazec.comboBox_izdelki.ItemsSource = izdelki

def izdelki():
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_NTPE
    worker.RunWorkerCompleted += bg_izdelki
    obrazec.comboBox_izdelki.ItemsSource = None
    obrazec.label_status.Content = 'Poizvedbe za izdelki'
    worker.RunWorkerAsync(["SELECT DISTINCT `Program` FROM `sledljivost`.`asysaba04` ORDER BY `Program`;", "{Program}"])

# operaterji
def bg_operaterji(sender, args):
    obrazec.label_status.Content = ''
    obrazec.comboBox_operaterji.ItemsSource = args.Result

def operaterji():
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_PRIS
    worker.RunWorkerCompleted += bg_operaterji
    obrazec.comboBox_operaterji.ItemsSource = None
    obrazec.label_status.Content = 'Poizvedbe za operaterji'
    worker.RunWorkerAsync(["SELECT [ID], [KONTROLOR], [IME], [DELSTEV] FROM [KAKOVOST].[dbo].[SEZKONTROLORJEV] WHERE [STATUS] = 0 ORDER BY [IME];", "{ID}\t{KONTROLOR} {IME}"])

# operacije
def bg_operacije(sender, args):
    obrazec.label_status.Content = ''
    obrazec.comboBox_operacije.ItemsSource = args.Result

def operacije():
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_PRIS
    worker.RunWorkerCompleted += bg_operacije
    obrazec.comboBox_operacije.ItemsSource = None
    obrazec.label_status.Content = 'Poizvedbe za operacijami'
    worker.RunWorkerAsync(["SELECT [ATE], [ZNAK] FROM [KAKOVOST].[dbo].[SEZATE] ORDER BY [ID];", "{ZNAK}\t{ATE}"])


# delovni nalogi
def bg_DNi_za_izdelek(sender, args):
    obrazec.label_status.Content = ''
    dn = args.Result
    obrazec.comboBox_delnalogi.ItemsSource = dn
    brisiznake()

def bg_Sprememba_cb_napake(sender, args):
    obrazec.label_status.Content = ''
    napake = args.Result
    obrazec.comboBox_pozicije_napake.ItemsSource = napake

def izdelek_changed(sender, args):
    try:
        brisiznake()
        worker1 = BackgroundWorker()
        worker1.DoWork += bg_Poizvedba_NTPE
        worker1.RunWorkerCompleted += bg_DNi_za_izdelek
        worker2 = BackgroundWorker()
        worker2.DoWork += bg_Poizvedba_PRIS
        worker2.RunWorkerCompleted += bg_Sprememba_cb_napake
        obrazec.comboBox_pozicije_napake.ItemsSource = None
        obrazec.comboBox_delnalogi.ItemsSource = None
        obrazec.label_status.Content = 'Poizvedba za del. nalogi in napakami'
        print(obrazec.comboBox_izdelki.SelectedItem.ToString())
        worker2.RunWorkerAsync(["SELECT [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] FROM [KAKOVOST].[dbo].[KOSOVNICE], [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[KODA]=(SELECT [ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KODA]='%s') AND [KAKOVOST].[dbo].[SEZMATERIALOV].[ID] = [KAKOVOST].[dbo].[KOSOVNICE].[MAT];" %obrazec.comboBox_izdelki.SelectedItem.ToString(), "{POZICIJA}"])
        worker1.RunWorkerAsync(["SELECT DISTINCT `DN` FROM `sledljivost`.`asysaba04` WHERE `Program` = '%s'" %obrazec.comboBox_izdelki.SelectedItem.ToString(), "{DN}"])
        osvezi_kolicine()
    except Exception as e:
        debug.TraceDbg("Napaka!", e.message.ToString(), "Warning")

# dummy procesna stevilka
def dummyprocesna_changed(sender, args):
    if (obrazec.textBox_dummyprocesna.Text.Length != 10):
        return
    else:
        try:
            obrazec.comboBox_izdelki.SelectedItem = None
            obrazec.comboBox_delnalogi.SelectedItem = None
            obrazec.comboBox_operaterji.SelectedItem = None
            obrazec.comboBox_operacije.SelectedItem = None
            obrazec.label_status.Content = 'Poizvedba za izdelkom ter delovnim nalogom %s' %obrazec.textBox_dummyprocesna.Text
            izdelek = poizvedbaNTPE("SELECT `Program` FROM `sledljivost`.`asysaba04` WHERE `Procesna` = '%s'" %obrazec.textBox_dummyprocesna.Text, "{Program}")[0]
            delnalog = poizvedbaNTPE("SELECT `DN` FROM `sledljivost`.`asysaba04` WHERE `Procesna` = '%s'" %obrazec.textBox_dummyprocesna.Text, "{DN}")[0]
            debug.TraceDbg("Informacije za %s" %obrazec.textBox_dummyprocesna.Text, "Izdelek: %s\nDN: %s" %(izdelek, delnalog), "Info")
            obrazec.comboBox_izdelki.SelectedItem = izdelek
            obrazec.comboBox_delnalogi.SelectedItem = delnalog
            obrazec.label_status.Content = ''
            stop(0)
        except Exception as e:
            debug.TraceDbg("Procesna %s ne obstaja!" %obrazec.textBox_dummyprocesna.Text, e.message.ToString(), "Warning")
            stop("Procesna %s ne obstaja!" %obrazec.textBox_dummyprocesna.Text, 1)


def bg_Sprememba_tb_identnapake(sender, args):
    ident = args.Result
    obrazec.textBox_ident_napake.Text = ident[0]

def bg_Sprememba_tb_material(sender, args):
    material = args.Result
    obrazec.textBox_material_napake.Text = material[0]

def bg_Sprememba_cb_napakeopis(sender, args):
    napake = args.Result
    obrazec.comboBox_napake_napake.ItemsSource = napake

def bg_Sprememba_cb_napakeopis_id(sender, args):
    napake = args.Result
    obrazec.comboBox_napake_napake.Tag = napake

def napake_napake_changed(sender, args):
    try:
        ID = obrazec.comboBox_napake_napake.Tag
        print("ID napake %s je %s !" %(obrazec.comboBox_napake_napake.SelectedItem.ToString(), ID[obrazec.comboBox_napake_napake.SelectedIndex]))
    except Exception as e:
        print(e.ToString())

def pozicija_napake_changed(sender, args):
    #Pobrisemo spisek starih napak
    obrazec.textBox_ident_napake.Text = ''
    obrazec.textBox_material_napake.Text = ''
    obrazec.comboBox_napake_napake.ItemsSource = None
    obrazec.comboBox_napake_napake.Items.Clear()
    if (obrazec.comboBox_pozicije_napake.SelectedItem == None):
        return
    #ident
    worker_ident = BackgroundWorker()
    worker_ident.DoWork += bg_Poizvedba_PRIS
    worker_ident.RunWorkerCompleted += bg_Sprememba_tb_identnapake
    worker_ident.RunWorkerAsync(["SELECT [KAKOVOST].[dbo].[KOSOVNICE].[IDENT] FROM [KAKOVOST].[dbo].[KOSOVNICE], [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[KODA]=(SELECT [ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KODA]='%s') AND [KAKOVOST].[dbo].[SEZMATERIALOV].[ID] = [KAKOVOST].[dbo].[KOSOVNICE].[MAT] AND [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s';" %(obrazec.comboBox_izdelki.SelectedItem.ToString(), obrazec.comboBox_pozicije_napake.SelectedItem.ToString()), "{IDENT}"])
    #material
    worker_mat = BackgroundWorker()
    worker_mat.DoWork += bg_Poizvedba_PRIS
    worker_mat.RunWorkerCompleted += bg_Sprememba_tb_material
    worker_mat.RunWorkerAsync(["SELECT [MATERIAL] FROM [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE ID=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[MAT] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s'));" %(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{MATERIAL}"])
    #napake
    worker_napakeopis = BackgroundWorker()
    worker_napakeopis.DoWork += bg_Poizvedba_PRIS
    worker_napakeopis.RunWorkerCompleted += bg_Sprememba_cb_napakeopis
    worker_napakeopis.RunWorkerAsync(["SELECT [NAPAK], [OPIS] FROM [KAKOVOST].[dbo].[SEZNAPAKN] WHERE [KRAJ]=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[KRAJ] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s')) ORDER BY [NAPAK]; "%(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{NAPAK}: {OPIS}"])
    worker_napakeopis_id = BackgroundWorker()
    worker_napakeopis_id.DoWork += bg_Poizvedba_PRIS
    worker_napakeopis_id.RunWorkerCompleted += bg_Sprememba_cb_napakeopis_id
    worker_napakeopis_id.RunWorkerAsync(["SELECT [OLD] FROM [KAKOVOST].[dbo].[SEZNAPAKN] WHERE [KRAJ]=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[KRAJ] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s')) ORDER BY [NAPAK]; "%(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{OLD}"])

def StartHooker(start = 0):
    if (start):
        print("Snifer vhoda je zagnan")
        debug.textBox_logging.TextChanged += hookerchangedP
        debug.textBox_logging.TextChanged += hookerchangedZ
        debug.checkBox_keyhooker.IsChecked = True
    else:
        print("Snifer vhoda je ustavljen")
        debug.textBox_logging.TextChanged -= hookerchangedP
        debug.textBox_logging.TextChanged -= hookerchangedZ
        debug.checkBox_keyhooker.IsChecked = False

# Pridobitev spiska procesne-serijske (offline rezim)
def podatki(sender, args):
    global Procesne


    if (obrazec.comboBox_delnalogi.SelectedItem == None or obrazec.comboBox_delnalogi.SelectedItem == ''):
        tip.Visibility = System.Windows.Visibility.Hidden
        status.Visibility = System.Windows.Visibility.Hidden
        return
    Procesne.Clear()
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_NTPE
    obrazec.label_status.Content = 'Poizvedbe PN'
    worker.RunWorkerCompleted += bg_SpisekProcesnih
    worker.RunWorkerAsync(["SELECT DISTINCT Substring(Procesna,1,9) FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Rezultat` LIKE 'PASS%%';" %obrazec.comboBox_delnalogi.SelectedItem.ToString(), "{Substring(Procesna,1,9)}"])
   
    osvezi_kolicine()


    

def operacije_changed(sender, args):
    brisiznake()
    osvezi_kolicine()

def bg_SpisekProcesnih(sender, args):
    global Procesne
    Procesne.Clear()
    Procesne = args.Result
    obrazec.label_status.Content = ''
    worker = BackgroundWorker()
    worker.DoWork += bg_SpisekSerijskih
    worker.RunWorkerCompleted += TipStatusNaloga
    obrazec.label_status.Content = 'SAP Poizvedbe SN/PN'
    worker.RunWorkerAsync([obrazec.comboBox_delnalogi.SelectedItem.ToString()])


def bg_SpisekSerijskih(sender, args):
    global Procesne
    global SerijskeSAP
    global ProcesneSAP
    global tip_naloga
    global status_naloga
    SerijskeSAP.Clear()
    ProcesneSAP.Clear()
    poizvedbaSAP(args.Argument[0])
    try:
        ZSAP = "n/a"
        PSAP = "n/a"
        print("Poizvedba za %i(%i) zapisov (tip DN: %s, status DN: %s)" %(Procesne.Count, ProcesneSAP.Count, tip_naloga, status_naloga))
        for i in range(Procesne.Count):
            ZSAP = "n/a"
            PSAP = "n/a"
            for j in range(ProcesneSAP.Count):

                if (ProcesneSAP[j].IndexOf(Procesne[i]) != -1):
                    PSAP = ProcesneSAP[j]
                    ZSAP = SerijskeSAP[j] 
            print("%i. %s - %s %s" %(i+1, Procesne[i],PSAP,ZSAP))

    except Exception as e:
        print(e.ToString())
       
def TipStatusNaloga(sender, args):
    global tip_naloga
    global status_naloga
    global TIPINALOGOV
    global STATUSINALOGOV
    try:
        tip.Visibility = System.Windows.Visibility.Visible
        status.Visibility = System.Windows.Visibility.Visible
        status.Content = status_naloga
        tip.Content = tip_naloga
        status.ToolTip = STATUSINALOGOV[status_naloga]
        tip.ToolTip = TIPINALOGOV[tip_naloga]
    except Exception as e:
        print(e.ToString())

# Keyhooker funkcije

def hookerchangedP(sender, args):
    serialP=Regex("P[0-9]{8}[A|B]")
    if (serialP.IsMatch(debug.textBox_logging.Text)):
        procesnast = serialP.Match(debug.textBox_logging.Text).Value
        debug.TraceDbg("Procesna se je ujela %s!" %procesnast, None, "Info")
        obdelajP(procesnast.Substring(0,9))
        debug.textBox_logging.Clear()

def hookerchangedZ(sender, args):
    serialZ=Regex("Z[0-9]{8}[G|H]")
    if (serialZ.IsMatch(debug.textBox_logging.Text)):
        serijskast = serialZ.Match(debug.textBox_logging.Text).Value
        debug.TraceDbg("Serijska se je ujela %s!" %serijskast, None, "Info")
        obdelajS(serijskast)
        debug.textBox_logging.Clear()

# socket funkcije
class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        podatki = self.data.ToString().Split(' ')
        if (podatki.Length == 1):
            debug.TraceDbg("%s wrote: %s" %(self.client_address[0], self.data), "SERIAL: %s" %podatki[0], "Info")
            obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](rezultat_testa), podatki[0])
        elif (podatki.Length == 2):
            if (podatki[0] == "PARALLEL"):
                paralelno_environment(podatki[1])
            else:
                debug.TraceDbg("%s wrote: %s" %(self.client_address[0], self.data), "SERIAL: %s REZULTAT: %s" %(podatki[0], podatki[1]), "Info")
                obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object, object](rezultat_testa), podatki[0], podatki[1])
        else:
            return
       
 
def rezultat_testa(serijska, res="n/a"):
    if ((serijska != obrazec.label1_serijska_vobdelavi.Text.ToString()) and (res!="n/a")):
        Windows.MessageBox.Show("Serijska testiranca se ne ujema s spremnim listom!", "Rezultat testiranja", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
        return
    if (res == "n/a"):
        obdelajS(serijska)
        return
    obrazec.label1_rezultat_vobdelavi.Text = res
    StanjeIzdelka.some_value = 2

def serve_on_port(port):
    HOST, PORT = "127.0.0.1", port
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

# obdelovanje izdelka
def find(l, elem):
    for row, i in enumerate(l):
        try:
            column = i.index(elem)
        except ValueError:
            continue
        return row, column
    return -1

def obdelajP(procesna):
    global ID_izdelka
    global Procesne
    global SerijskeSAP
    global ProcesneSAP
    global timer
    indexNTPE = Procesne.IndexOf(procesna)
    indexSAP = None
    obrazec.tabItem3.IsEnabled = 0
    ID_izdelka = None
    obrazec.label1_rezultat_vobdelavi.Text = "n/a"    
    if (indexNTPE != -1):
        for PSAP in ProcesneSAP:
            if (PSAP.IndexOf(procesna) != -1):
                indexSAP = ProcesneSAP.IndexOf(PSAP)
        obrazec.label1_procesna_vobdelavi.Text = procesna
        if (indexSAP != None):
            obrazec.label1_serijska_vobdelavi.Text = SerijskeSAP[indexSAP]
        else:
            obrazec.label1_serijska_vobdelavi.Text = "n/a"
        if (preveriprocesno(obrazec.label1_procesna_vobdelavi.Text) == 0):
            StanjeIzdelka.some_value = 1
            lb_stevec.Content = 0
            timer.Start()
    else:
        obrazec.label1_procesna_vobdelavi.Text = "ERROR"
        obrazec.label1_serijska_vobdelavi.Text = "ERROR"
        StanjeIzdelka.some_value = 0

def obdelajS(serijska):
    global Procesne
    global SerijskeSAP
    global ProcesneSAP
    global ID_izdelka
    global timer
    index = SerijskeSAP.IndexOf(serijska)
    obrazec.tabItem3.IsEnabled = 0
    ID_izdelka = None
    obrazec.label1_rezultat_vobdelavi.Text = "n/a"
    indexSAP = SerijskeSAP.IndexOf(serijska)
    if (indexSAP != -1):
        PSAP = ProcesneSAP[indexSAP]
        if (PSAP.Length == 10):
            procesna_indeks = Procesne.IndexOf(PSAP.Substring(0,9))
            if (procesna_indeks != -1):
                procesna = Procesne[procesna_indeks]
            else:
                procesna = PSAP
        else:
            procesna = PSAP
        obrazec.label1_procesna_vobdelavi.Text = procesna
        if (indexSAP != None):
            obrazec.label1_serijska_vobdelavi.Text = SerijskeSAP[indexSAP]
        else:
            obrazec.label1_serijska_vobdelavi.Text = "n/a"
        if (preveriprocesno(obrazec.label1_procesna_vobdelavi.Text) == 0):
            StanjeIzdelka.some_value = 1
            lb_stevec.Content = 0
            timer.Start()
    else:
        obrazec.label1_procesna_vobdelavi.Text = "ERROR"
        obrazec.label1_serijska_vobdelavi.Text = "ERROR"
        StanjeIzdelka.some_value = 0


# PASS in FAIL odlocitev, vpis NAPAKE
def click_PASS(sender, args):
    try:
        #global cb_izhod
        global ID_izdelka
        global timer
        global lb_stevec
        if (StanjeIzdelka.some_value == 2 or StanjeIzdelka.some_value == 1 or StanjeIzdelka.some_value == 4):
            insert_stavek = ("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST, DURATION) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s', %s); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Text, obrazec.label1_serijska_vobdelavi.Text, obrazec.comboBox_delnalogi.SelectedItem.ToString(),
                               obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               0, obrazec.label1_rezultat_vobdelavi.Text, lb_stevec.Content))
            timer.Stop()
            ID = poizvedbaPRIS(insert_stavek, "{}")
            if (ID != None):
                ID_izdelka = ID[0]
                ok("Izdelek vpisan kot PASS, ID vpisa %s" %ID_izdelka, 1)
                StanjeIzdelka.some_value = 3
            else:
                stop("NI ID-ja", 1)
                Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
        else:
            if (StanjeIzdelka.some_value == 3):
                stop("Vpis v bazo je ze bil izveden!", 1)
                return
            else:
                stop("Vpis v bazo ni mozen zaradi pomanjkljivih podatkov!", 1)
                return

        osvezi_kolicine()
    except Exception as e:
        stop("VPIS: Prislo je do nenadzorovane napake. Poglej v debug okno!", 1)
        debug.TraceDbg("VPIS: Prislo je do nenadzorovane napake pri vpisu v bazo", "%s" %(e.message.ToString()), "Warning")

def click_FAIL(sender, args):
    try:
        global ID_izdelka
        global timer
        global lb_stevec
        if (StanjeIzdelka.some_value == 2 or StanjeIzdelka.some_value == 1 or StanjeIzdelka.some_value == 3):
            insert_stavek = ("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST, DURATION) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s', %s); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Text, obrazec.label1_serijska_vobdelavi.Text, obrazec.comboBox_delnalogi.SelectedItem.ToString(),
                               obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               2, obrazec.label1_rezultat_vobdelavi.Text, lb_stevec.Content))
            timer.Stop()
            ID = poizvedbaPRIS(insert_stavek, "{}")
            if (ID != None):
                ID_izdelka = ID[0]
                ok("Izdelek vpisan kot FAIL, ID vpisa %s" %ID_izdelka, 1)
                StanjeIzdelka.some_value  = 4
            else:
                stop("NI ID-ja", 1)
                Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
        else:
            if (StanjeIzdelka.some_value == 4):
                stop("Vpis v bazo je ze bil izveden!", 1)
            else:
                stop("Vpis v bazo ni mozen zaradi pomanjkljivih podatkov!", 1)
        osvezi_kolicine()
    except Exception as e:
        stop("Prislo je do nenadzorovane napake. Poglej v debug okno!", 1)
        debug.TraceDbg("Prislo je do nenadzorovane napake pri vpisu v bazo", "%s" %(e.message.ToString()), "Warning")

def click_VPISINAPAKO(sender, args):  # vpis napake
    porocilo = ""
    try:
        global form
        print(form.opomba)
        global ID_izdelka
        global Opomba
        if (ID_izdelka == None):
            ID_izdelka = 0
        ID_napake = obrazec.comboBox_napake_napake.Tag[obrazec.comboBox_napake_napake.SelectedIndex]
        if (StanjeIzdelka.some_value == 2 or StanjeIzdelka.some_value == 1 or StanjeIzdelka.some_value == 3 or StanjeIzdelka.some_value == 4):
            insert_stavek = ("INSERT INTO SPREMNILISTNAPAK (PROCESNA, OPERACIJA, OPERATER, POZICIJA, NAPAKA, OPIS, ID_IZDELEK) VALUES ('%s', '%s', %s, '%s', %s, '%s', %s); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Text,  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), ID_napake, Opomba, ID_izdelka))
            ID = poizvedbaPRIS(insert_stavek, "{}")
            if (ID != None):
                ID_napake = ID[0]
                porocilo += "Napaka izdelka vpisana, ID vpisa %s. " %ID_napake
            else:
                stop("NI ID-ja", 1)
                Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
           
            if (obrazec.checkBox_izloci.IsChecked == 1):
                ID = poizvedbaPRIS("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Text, obrazec.label1_serijska_vobdelavi.Text, obrazec.comboBox_delnalogi.SelectedItem.ToString(),
                               obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               5, obrazec.label1_rezultat_vobdelavi.Text), "{}")
                porocilo += "Izdelek vpisan kot KARANTENA, ID vpisa %s" %ID_izdelka
            ok(porocilo, 1)
            Opomba = ''
        else:
            if (StanjeIzdelka.some_value == 0):
                stop("Vpis v bazo je ze bil izveden!", 1)
            else:
                stop("Vpis v bazo ni mozen zaradi pomanjkljivih podatkov!", 1)
    except Exception as e:
        stop("Prislo je do nenadzorovane napake. Poglej v debug okno!", 1)
        debug.TraceDbg("Prislo je do nenadzorovane napake pri vpisu v bazo", "%s" %(e.message.ToString()), "Warning")    
   
# Preverjanje procesne izdelka - je ze bil v obdelavi, ima kaksne napaka ...
def preveriprocesno(procesna):
    try:
        izdelek_iz_procesne = poizvedbaNTPE("SELECT `Program` FROM `sledljivost`.`asysaba04` WHERE `Procesna` LIKE '%s%%'" %procesna.Substring(0,9), "{Program}")
        dn_iz_procesne = poizvedbaNTPE("SELECT `DN` FROM `sledljivost`.`asysaba04` WHERE `Procesna` LIKE '%s%%'" %procesna.Substring(0,9), "{DN}")
        napake_s = 0
        napake_w = 0
        napake_i = 0
        Opis_Napake_s = ''
        Opis_Napake_w = ''
        Opis_Napake_i = ''
        brisiznake()
        # Preverba izbranega DN (+ERROR)
        if (izdelek_iz_procesne.Count > 0 and dn_iz_procesne.Count > 0):
            if (izdelek_iz_procesne[0] != obrazec.comboBox_izdelki.Text):
                napake_s+=1
                Opis_Napake_s+='NTPE: Izdelek (%s) ne ustreza testnemu postopku (%s)\n' %(procesna, izdelek_iz_procesne[0])
            if (dn_iz_procesne[0] != obrazec.comboBox_delnalogi.Text):
                napake_s+=1
                Opis_Napake_s+='NTPE: Izdelek (%s) ni del delovnega naloga (%s)\n' %(procesna, dn_iz_procesne[0])
        else:
            napake_s+=1
            Opis_Napake_s+='NTPE: Procesna (%s) ne obstaja v sistemu!\n' %procesna

        # Ali je imela plosca napake na predhodnih operacijah (+WARNING)
        for napake in poizvedbaPRIS("SELECT ID, OPERACIJA, POZICIJA, NAPAKA FROM KAKOVOST.dbo.SPREMNILISTNAPAK WHERE PROCESNA = '%s';" %(procesna), "{ID},{OPERACIJA},{POZICIJA},{NAPAKA}"):
            napake_w+=1
            podatki = napake.Split(',')
            Opis_Napake_w+='Napaka na operaciji %s: pozicija %s, napaka %s: %s\n' %(podatki[1], podatki[2], poizvedbaPRIS("SELECT NAPAK FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{NAPAK}")[0], poizvedbaPRIS("SELECT OPIS FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{OPIS}")[0])

        # Ali je bila plosca ze prej stestirana (+INFO)
        stevilotestiranj = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s';" %(procesna.ToString().Substring(0,9),  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{}")[0])

        if (stevilotestiranj > 0):
            napake_i+=1
            stevilotestiranjPASS = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s' AND REZULTAT = 0;" %(procesna.ToString().Substring(0,9),  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{}")[0])
            stevilotestiranjFAIL = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s' AND REZULTAT = 2;" %(procesna.ToString().Substring(0,9),  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{}")[0])
            zadnjirezultat = poizvedbaPRIS("SELECT REZULTAT FROM SPREMNILISTREZULTAT WHERE ID = (SELECT TOP 1 REZULTAT FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s' ORDER BY DATUM DESC);" %(procesna.ToString().Substring(0,9),  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{REZULTAT}")[0]
           
            obrazec.tabItem3.IsEnabled = 1


            Opis_Napake_i+='Plosca je ze bila %sx na tem testu! %sx PASS, %sx FAIL. \nZadnje stanje plosce je %s.\n' %(stevilotestiranj, stevilotestiranjPASS, stevilotestiranjFAIL, zadnjirezultat)

        if (napake_s > 0):
            stop(Opis_Napake_s, 1)
        if (napake_w > 0):
            warning(Opis_Napake_w, 1)
        if (napake_i > 0):
            info(Opis_Napake_i, 1)

        if (napake_s == 0):
            return 0
        else:
            return -1
    except Exception as e:
        stop("Glava spremnega lista ni izpolnjena!", 1)
        return -1

def vhosopombe(sender, args):
    form = MyForm()
    form.Show()
    #Application.Run(form)


###########
# M A I N #
###########

lb_nalog = Label()
lb_pass = Label()
lb_fail = Label()
lb_out = Label()
lb_todo = Label()
lb_stevec = Label()
tip = Label()
status = Label()
obrazec.stackPanel2.Children.Add(tip)
obrazec.stackPanel2.Children.Add(status)


izdelki()
operaterji()
operacije()
init()
form = MyForm()
obrazec.comboBox_izdelki.SelectionChanged += izdelek_changed
obrazec.comboBox_pozicije_napake.SelectionChanged += pozicija_napake_changed
obrazec.textBox_dummyprocesna.TextChanged += dummyprocesna_changed
obrazec.comboBox_delnalogi.SelectionChanged += podatki
obrazec.comboBox_operacije.SelectionChanged += operacije_changed
obrazec.button_opombe.Click += vhosopombe
StartHooker(True)
t = threading.Thread(target=serve_on_port, args=[9999])
t.setDaemon(True)
t.start()
obrazec.button_green.Click += click_PASS
obrazec.button_red.Click += click_FAIL
obrazec.button_vpisi.Click += click_VPISINAPAKO
#obrazec.label1_rezultat_vobdelavi.IsReadOnly = 0
